<?php
namespace Manager\Controller;
/**
* ==============================================
* URL：http://www.liuhuanhui.cn
* ==============================================
* @date：2014-10-23
* @time：上午9:51:15
* @author：liuhuanhui
* @encoding：UTF-8
*/
class UserController extends  AuthController//用户控制器
{
	/**
	 * 显示所有用户信息
	 */
	function  index()
	{
		$users=D('UsersView')->order('id')->select();
		$data=array();
		foreach ($users as $user)
		{
			$user[role]='<kbd>'.$user[role].'</kbd>';
			if(!array_key_exists($user[id], $data))
				$data[$user[id]]=$user;
			else
				$data[$user[id]][role].=$user[role];
		}			
		$this->assign('users',$data);
		$this->roles=M('auth_group')->field('id,title')->select();
		$this->display();
	}
	/**
	 * 设置用户状态（启用或者禁用）
	 */
	function setEnable()
	{
		$data=array(id=>I('id'),enable=>I('enable'));
		if(M('users')->save($data))
			$this->success('改变用户状态成功！',U('index'));
		else
			$this->error('改变用户状态失败！');
	}
	/**
	 * 添加用户和编辑
	 */
	function create()
	{	
		if(I('id'))
		$this->user=M('users')->find(I('id'));
		$this->roles=M('auth_group')->field('id,title')->select();
		$this->display();
	}
	/**
	 * 添加用户和修改用户处理方法
	 */
	function createHandle()
	{
				$userDate=array(
				username=>I('txt_name'),
				nickname=>I('txt_nickname'),
				head=>I('txt_head'),
				email=>I('txt_email'),
				url=>I('txt_url'),
				qq=>I('txt_qq'),
				userpassword=>I('txt_password','','md5'),
		);
		$userModel=M('users');
		if(I('id'))
		{
			if(($userModel->where('id='.I('id'))->save($userDate)))
				$this->success('修改用户信息成功！',U('index'));
			else
				$this->error('修改用户信息失败！');
		}else{
			$userModel->startTrans();
			$userId=$userModel->add($userDate);
			$roleDate=array(uid=>$userId,group_id=>I('txt_role'));
			$role=M('auth_group_access')->add($roleDate);
			if($userId&&$role)
			{
				$userModel->commit();
				$this->success('添加新的用户成功！',U('index'));
			}
			else{
				$userModel->rollback();
				$this->error('添加用户失败，所有信息已经回滚！');
			}
		}
	}
	
}